package com.iwop.moto.controller.web;

import com.alibaba.fastjson.JSON;
import com.iwop.moto.auth.LoginAuth;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.controller.BaseController;
import com.iwop.moto.model.ResultModel;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.service.BUserService;
import com.iwop.moto.service.IDataService;
import com.iwop.moto.service.YunxinService;
import com.iwop.moto.utils.api.YunXin.YunXinUtils;
import com.iwop.moto.utils.stringUtil.ObjectId;
import com.iwop.moto.utils.stringUtil.SequenceUtil;
import com.iwop.moto.utils.stringUtil.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.Time;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mobom on 2016/10/10.
 */
@Controller
public class BUserConroller extends BaseController {

    @Autowired
    private BUserService bUserService;
    @Autowired
    private IDataService dataService;
    @Autowired
    private YunxinService yunxinService;

    Logger logger=Logger.getLogger(BUserConroller.class);

    @RequestMapping("/api/buser/login")
    @ResponseBody
    public ResultModel login(HttpServletRequest request){
        try {
            ResultModel resultModel=new ResultModel();
            SuperRecordModel SRModel = this.getSRModel();
            String code1 = SRModel.getString("code").toUpperCase();
            String code = (String)getValueFromSession(code1);
            if(StringUtils.isEmpty(SRModel.getString("code"))){
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.USER_CODE_ISEXIST);
                return resultModel;
            }
            if(StringUtils.isEmpty(code)){
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.USER_CODE_ISEXIST);
                return resultModel;
            }
            if(StringUtils.isEmpty(SRModel.getString("pwd")) || StringUtils.isEmpty(SRModel.getString("login_code"))){
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.ERROR_PARAMETER);
                return resultModel;
            }
            SuperRecordModel srm=bUserService.getUser(SRModel);
            if(srm==null){//用户不存在
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.USER_ERROR_NOEXIST);
                return resultModel;
            } else if(!srm.getString("pwd").equals(SRModel.getString("pwd"))){
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.USER_ERROR_USERORPWD);
                return resultModel;
            }
            if(!(srm.getString("dataname").equals("管理员")||srm.getString("login_code").equals("admin"))){
                Object starttimes = srm.get("starttime");
                LocalTime starttime = ((Time) starttimes).toLocalTime();
                LocalTime endtime = ((Time) srm.get("endtime")).toLocalTime();
                LocalTime now = LocalTime.now();
                if(!(starttime.isBefore(now)&&endtime.isAfter(now))){
                    resultModel.setCode(0);
                    resultModel.setMem(ErrCode.USER_NOT_WORK);
                    return resultModel;
                }
            }
            putValueFromSession(srm.getString("sid"),srm,86000); /** 存入 Redis 缓存中 **/
            srm.remove("pwd");
            SuperRecordModel sprm=bUserService.getBUserLogByLoginCode(SRModel);
            if(sprm==null){
                srm.put("lastLoginTime",new Date());
            }else {
                srm.put("lastLoginTime",sprm.get("login_time"));
            }
            SuperRecordModel superRecordModel=new SuperRecordModel();
            superRecordModel.put("id",ObjectId.UUID());
            superRecordModel.put("login_time",new Date());
            superRecordModel.put("login_code",SRModel.getString("login_code"));
            superRecordModel.put("ip",getIpAddr(request));
            bUserService.insertBUserLog(superRecordModel);
            resultModel.setData(JSON.toJSONString(srm));
            return resultModel;
        }catch (Exception e){
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    //获取ip地址
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    @RequestMapping("/api/buser/register")
    @ResponseBody
    @LoginAuth(isval=true)
    public ResultModel registerBUser(HttpServletRequest request){
        try {
            ResultModel resultModel=new ResultModel();
            SuperRecordModel SRModel = this.getSRModel();
            String sid = ObjectId.userUUID();
            SRModel.put("sid",sid);
            SRModel.put("addtime",new Date());
            SuperRecordModel srm =bUserService.getBUserByLoginCode(SRModel);
            if(srm!=null){
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.USER_ERROR_ISEXIST);
                return resultModel;
            }
            if(!SRModel.containsKey("login_code")){
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.USER_ERROR_LOGINCODE);
                return resultModel;
            }
            SuperRecordModel superRecordModel=new SuperRecordModel();
            superRecordModel.put("codetype","Work");
            superRecordModel.put("datavalue","ZZ");
            SuperRecordModel dataByCodeTypeEx = dataService.findDataByCodeTypeEx(superRecordModel);
            SRModel.put("status",dataByCodeTypeEx.getString("sid"));
            SuperRecordModel sModel=new SuperRecordModel();
            sModel.put("sid",SRModel.getString("session_id"));
            SuperRecordModel bUserByLoginCode = bUserService.getBUserBySid(sModel);
            if(!(bUserByLoginCode.getString("login_code").equals("admin")||bUserByLoginCode.getString("area_code").equals("JSFP"))){
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.NOT_VISIT_INVALID);
                return resultModel;
            }
            bUserService.insertBUser(SRModel);
            createIMUser(SRModel);
            return resultModel;
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    private boolean createIMUser(SuperRecordModel SRModel){
        try{
            String token = SequenceUtil.Serial("S");
            String result = YunXinUtils.addIMUser(SRModel.getString("sid"), SRModel.getString("login_code"),null, token);
            Map parse = (Map)JSON.parse(result);
            int code = (int)parse.get("code");
            if(code==200){
                SuperRecordModel srm=new SuperRecordModel();
                srm.put("im_accid",SRModel.getString("sid"));
                srm.put("im_name",SRModel.getString("login_code"));
                //srm.put("im_icon",user.getImgpath());
                srm.put("im_token",token);
                yunxinService.insertIM(srm);
                return true;
            }else{
                logger.error("云信注册返回错误结果：" + result);
                logger.error("云信注册时间：" + new Date());
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @RequestMapping("/api/buser/update")
    @ResponseBody
    @LoginAuth(isval=true)
    public ResultModel updateBUser(HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        SuperRecordModel SRModel = this.getSRModel();
        SuperRecordModel smo=new SuperRecordModel();
        smo.put("sid",SRModel.getString("session_id"));
        SuperRecordModel srm =bUserService.getBUserBySid(smo);
        if(srm==null){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_NOEXIST);
            return resultModel;
        }
        if(srm==null){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_ISEXIST);
            return resultModel;
        }
        if(!StringUtils.isEmpty(SRModel.getString("pwd"))){
            if(!srm.getString("login_code").equals("admin")){
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.NOT_VISIT_INVALID);
                return resultModel;
            }
        }
        if(!(srm.getString("login_code").equals("admin")||srm.getString("role_code").equals("GLY")||srm.getString("area_code").equals("JSFP"))){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.NOT_VISIT_INVALID);
            return resultModel;
        }
        if(!srm.getString("weeks").contains(StringUtils.getWeek(new Date()))){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_NOT_WORK);
            return resultModel;
        }
        SuperRecordModel superRecordModel=new SuperRecordModel();
        superRecordModel.put("sid",ObjectId.UUID());
        superRecordModel.put("content",SRModel.getString("notice"));
        superRecordModel.put("user_id",SRModel.getString("sid"));
        superRecordModel.put("addtime",new Date());
        superRecordModel.put("apply_user",SRModel.getString("session_id"));
        bUserService.addUserUpdateLog(superRecordModel);
        bUserService.updateBUser(SRModel);
        return resultModel;
    }

    @RequestMapping("/api/buser/detail")
    @ResponseBody
    @LoginAuth(isval=true)
    public ResultModel getBUserDetail(){
        try {
            SuperRecordModel SRModel = this.getSRModel();
            SuperRecordModel bUserByLoginCode = bUserService.getBUserBySid(SRModel);
            List<SuperRecordModel> list=bUserService.getUserUpdateByLogincode(SRModel);
            bUserByLoginCode.put("notices",list);
            return getSucceed(bUserByLoginCode,ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    @RequestMapping("/api/buser/list")
    @ResponseBody
    @LoginAuth(isval=true)
    public ResultModel getBUserList(HttpServletRequest request){
        try {
            ResultModel resultModel=new ResultModel();
            SuperRecordModel SRModel = this.getSRModel();
            List<SuperRecordModel> srm =bUserService.getBUserList(SRModel);
            resultModel.setData(JSON.toJSONString(srm));
            return resultModel;
        }catch (Exception e){
            e.printStackTrace();
            return  getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 发布公告
     * */
    @RequestMapping("/api/buser/notice")
    @ResponseBody
    @LoginAuth(isval=true)
    public ResultModel addUserNotice(HttpServletRequest request){
        try {
            SuperRecordModel SRModel = this.getSRModel();
            if(SRModel.containsKey("content")&&StringUtils.isEmpty(SRModel.getString("content"))){
               return getErr(ErrCode.ERROR_SYSTEM);
            }
            SRModel.put("sid",ObjectId.UUID());
            SRModel.put("addtime",new Date());
            SRModel.put("user_id",SRModel.getString("session_id"));
            SRModel.put("status_flag","1");
           bUserService.addUserNotice(SRModel);
            return getSucceed(ErrCode.SUCCEED);
        }catch (Exception e){
            e.printStackTrace();
            return  getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 公告列表
     * */
    @RequestMapping("/api/buser/notice/list")
    @ResponseBody
    @LoginAuth(isval=true)
    public ResultModel userNoticeList(){
      try {
          SuperRecordModel SRModel = this.getSRModel();
          List<SuperRecordModel> list=bUserService.getUserNoticeList(SRModel);
          return getSucceed(list,ErrCode.SUCCEED);
      }catch (Exception e){
            return getErr(ErrCode.ERROR_SYSTEM);
      }
    }


}
